#!/bin/bash -e

function info() {
    echo Usage: `basename $0` 'ref_bed_prefix bed_prefix'
    exit 1
}

while getopts ":p:f:t:l:" opt; do
    case  $opt  in
        p) out_prefix=$OPTARG;;
        f) suffix=$OPTARG;;
        t) format=$OPTARG;;
        l) layout=$OPTARG;;
        *) info;;
    esac
done
shift $(($OPTIND - 1))

if [ $# -lt 1 ]; then info; fi

. $var

prefix1=$1
prefix2=$2
prefix=$out_prefix.merge
echo 1 > $out_prefix.poplist.txt

# plink --bfile $prefix1 --bmerge $prefix2.bed $prefix2.bim $prefix2.fam --make-bed --out $prefix

cat <<convert1 > $out_prefix.par.convert1.txt
genotypename:    $prefix1.bed
snpname:         $prefix1.bim
indivname:       $prefix1.fam
outputformat:    EIGENSTRAT
genotypeoutname: $prefix1.geno
snpoutname:      $prefix1.snp
indivoutname:    $prefix1.ind
familynames:     NO
convert1

cat <<convert2 > $out_prefix.par.convert2.txt
genotypename:    $prefix2.bed
snpname:         $prefix2.bim
indivname:       $prefix2.fam
outputformat:    EIGENSTRAT
genotypeoutname: $prefix2.geno
snpoutname:      $prefix2.snp
indivoutname:    $prefix2.ind
familynames:     NO
convert2


# convertf -p $out_prefix.par.convert1.txt
convertf -p $out_prefix.par.convert2.txt
# sed 's/^  *//; s/ /\t/' $prefix1.ind > $prefix1.ind1
sed 's/^  *//; s/ /\t/' $prefix2.ind > $prefix2.ind1
# awk 'BEGIN{OFS="\t"}{print $1, $2, "1"}' $prefix1.ind1 > $prefix1.ind2
awk 'BEGIN{OFS="\t"}{print $1, $2, "2"}' $prefix2.ind1 > $prefix2.ind2

cat <<merge > $out_prefix.par.merge.txt
geno1: $prefix1.geno
snp1:  $prefix1.snp
ind1:  $prefix1.ind2
geno2: $prefix2.geno
snp2:  $prefix2.snp
ind2:  $prefix2.ind2
genooutfilename:   $out_prefix.merge.geno
snpoutfilename:    $out_prefix.merge.snp
indoutfilename:    $out_prefix.merge.ind
merge
mergeit -p $out_prefix.par.merge.txt

# cut -f1-5 -d' ' $prefix.fam > $prefix.fam1-5
# num=`cat $prefix.fam|wc -l`
# rep.sh 1 $num|paste -d' ' $prefix.fam1-5 - > $prefix.fam1

cat <<par > $out_prefix.par.txt
genotypename:    $out_prefix.merge.geno
snpname:         $out_prefix.merge.snp
indivname:       $out_prefix.merge.ind
evecoutname:     $out_prefix.evec.txt
evaloutname:     $out_prefix.eval.txt
altnormstyle:    NO
numoutevec:      2
grmoutname:      $out_prefix.grmjunk
poplistname:     $out_prefix.poplist.txt
par

smartpca -p $out_prefix.par.txt > $out_prefix.pca.log
cat $out_prefix.evec.txt |sed '1d'|sed 's/^  *//; s/  */\t/g; s/  *$//' > $out_prefix.evec.1.txt
# ploteig -i $out_prefix.evec.txt -c 1:2 -p Control -x -o $out_prefix.plot.xtxt

unset PYTHONPATH
. ~/../fei.yang/yn/tools/conda/bin/activate py36

plot_pca.py $out_prefix.evec.1.txt


. $cmd_done
